package caiziyou.com.designpattern.prototype.deepclone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 字符串和基本数据类型会默认复制
 * 
 * @author Administrator
 *
 */
public class DeepProtoType implements Serializable, Cloneable {

	private String name;
	private int number;
	private DeepCloneTarget deepCloneTarget;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public DeepCloneTarget getDeepCloneTarget() {
		return deepCloneTarget;
	}

	public void setDeepCloneTarget(DeepCloneTarget deepCloneTarget) {
		this.deepCloneTarget = deepCloneTarget;
	}

	public DeepProtoType(String name, int number, DeepCloneTarget deepCloneTarget) {
		super();
		this.name = name;
		this.number = number;
		this.deepCloneTarget = deepCloneTarget;
	}

	@Override
	public String toString() {
		return "DeepProtoType [name=" + name + ", number=" + number + ", deepCloneTarget=" + deepCloneTarget + "]";
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		DeepProtoType clone = (DeepProtoType) super.clone();
		DeepCloneTarget target = (DeepCloneTarget) this.deepCloneTarget.clone();
		clone.setDeepCloneTarget(target);
		return clone;
	}

	public Object deepClone() {
		// 创建流对象
		ByteArrayOutputStream bos = null;
		ObjectOutputStream oos = null;
		ByteArrayInputStream bis = null;
		ObjectInputStream ois = null;
		try {
			// 序列化
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(this);

			// 反序列化
			bis = new ByteArrayInputStream(bos.toByteArray());
			ois = new ObjectInputStream(bis);
			return ois.readObject();
		} catch (Exception e) {
			System.out.println("深度复制失败");
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {

				}
			}

			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {

				}
			}

			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {

				}
			}

			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {

				}
			}
		}
		return null;
	}
}
